package com.ben.utils.util

import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.TypedValue
import android.widget.Toast
import kotlinx.coroutines.*

/**
 * 将ps值转换为px值
 * @return Int
 */
fun Float.sp(context: Context): Float {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP, this,
        context.resources.displayMetrics
    )
}

fun Int.dp(context: Context): Int {
    val density = context.resources.displayMetrics.density
    return (this * density + 0.5f).toInt()
}

fun <T> CoroutineScope.ioAsync(
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
    val deferred = async(Dispatchers.IO, start) {
        block()
    }
    return deferred
}

fun <T> Deferred<T>.then(block: (T) -> Unit) = GlobalScope.launch(Dispatchers.Main) {
    block(this@then.await())
}

fun Context.getDensityHeight(): Int {
    return resources.displayMetrics.heightPixels
}

fun Context.getDensityWidth(): Int {
    return resources.displayMetrics.widthPixels
}

fun Context.dip(): Float {
    return resources.displayMetrics.density
}

fun Context.getVersionCode(): Long {
    var versionCode = 0L
    try {
        val packageInfo = applicationContext.packageManager.getPackageInfo(
            packageName, 0
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            versionCode = packageInfo.longVersionCode
        } else {
            versionCode = packageInfo.versionCode.toLong()
        }
    } catch (e: PackageManager.NameNotFoundException) {

    }
    return versionCode
}

fun Context.getVersionName(): String {
    var appVersionName = "1.0"
    try {
        val packageInfo = applicationContext
            .packageManager
            .getPackageInfo(packageName, 0)
        appVersionName = packageInfo.versionName
    } catch (e: PackageManager.NameNotFoundException) {

    }
    return appVersionName
}

fun Context.showLongToast(text: String) {
    Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}

fun Context.showShortToast(text: String) {
    Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}